package 串联所有单词的子串;

import java.util.*;

class Solution {
    public List<Integer> findSubstring(String s, String[] words) {
        List<Integer> ret = new ArrayList<>();
        int m = words[0].length();
        int len1 = words.length;
        int n = m * len1;
        Map<String,Integer> map1 = new HashMap<>();
        for (String word : words) {
            map1.put(word,map1.getOrDefault(word,0) + 1);
        }
        int len2 = s.length();
        for (int i = 0; i < m; i++){
            HashMap<String,Integer> map2 = new HashMap<>();
            for (int left = i,right = i,count = 0; right <= len2; right += m){
                if (right - left == 0){
                    continue;
                }
                String tmp = s.substring(right - m, right);
                map2.put(tmp,map2.getOrDefault(tmp,0) + 1);
                if (map2.get(tmp) <= map1.getOrDefault(tmp,0)){
                    count++;
                }
                if (count == len1){
                    ret.add(left);
                }
                if (right - left + 1 > n){
                    tmp = s.substring(left,left + m);
                    map2.put(tmp,map2.get(tmp) - 1);
                    if (map2.get(tmp) < map1.getOrDefault(tmp,0)){
                        count--;
                    }
                    left += m;
                }
            }
        }
        return ret;
    }
}